package com.project.dao.impl;

import com.project.bean.CommentBean;
import com.project.bean.ThemeBean;
import com.project.bean.UserBean;
import com.project.dao.ICommentDao;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("all")
@Repository
public class CommentDaoImpl extends BaseDao implements ICommentDao {
    @Override
    public void add(CommentBean comment) {
        this.setConnection();
        try {
            ps = con.prepareStatement("insert into t_comment (c_name,c_content,c_date,fk_userId,fk_themeId) values (?,?,?,?,?);");
            ps.setObject(1,comment.getName());
            ps.setObject(2,comment.getContent());
            ps.setObject(3,comment.getDate());
            ps.setObject(4,comment.getUser().getId());
            ps.setObject(5,comment.getTheme().getId());

            ps.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            this.close();
        }
    }

    @Override
    public List<CommentBean> findByTheme(Integer id) {
        List<CommentBean> list = new ArrayList<>();
        this.setConnection();
        try {
            ps = con.prepareStatement("SELECT t.*,u.u_nickname FROM t_comment t LEFT JOIN t_user u ON t.fk_userId = u.pk_userId WHERE fk_themeId = ?");
            ps.setObject(1,id);

            rs = ps.executeQuery();
            while (rs.next()) {
                CommentBean comment = new CommentBean();
                comment.setId(rs.getInt("pk_commentId"));
                comment.setName(rs.getString("c_name"));
                comment.setContent(rs.getString("c_content"));
                UserBean user = new UserBean();
                comment.setUser(user);
                user.setId(rs.getInt("fk_userId"));
                user.setNickname(rs.getString("u_nickname"));
                ThemeBean theme = new ThemeBean();
                theme.setId(rs.getInt("fk_themeId"));
                comment.setTheme(theme);

                list.add(comment);

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            close();
        }
        return list;
    }
}
